package com.yunshipei.ui.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.common.Globals;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.wedigt.YspButton;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;
import org.reactivestreams.Subscription;

import butterknife.Bind;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;

public class ModifyPwdFragment extends BaseBodyFragment {

    public static ModifyPwdFragment newInstance(MainExtraBean mainExtraBean) {
        ModifyPwdFragment modifyPwdFragment = new ModifyPwdFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_CUSTOMER_MAIN_DATA, mainExtraBean);
        modifyPwdFragment.setArguments(bundle);
        return modifyPwdFragment;
    }

    @Bind(R.id.enter_title_bar)
    protected YspTitleBar mTitleBar;
    @Bind(R.id.reset_pass_ok)
    protected YspButton mConfirmButton;
    @Bind(R.id.et_first_line_new_pas)
    protected EditText mNewPassword;
    @Bind(R.id.et_confirm_line_new_pas)
    protected EditText mNewConfirmPassword;

    private SharedPreferences mPreferences;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
    }

    @Override
    public int viewLayout() {
        return R.layout.fragment_modify_pwd;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTitleBar.setTitle("修改密码");
        if (isPad()) {
            mTitleBar.setBackClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseUtil.hideKeyBoard(mContext);
                    EventBus.getDefault().post(new YspEvent.PadClick(SettingsFragment.class.getName()));
                }
            });
        }
        mConfirmButton.setBtnText("确定");
        mConfirmButton.setTopTvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newPassword = BaseUtil.replaceBlank(mNewPassword.getText().toString());
                String confirmPassword = BaseUtil.replaceBlank(mNewConfirmPassword.getText().toString());
                if (TextUtils.isEmpty(newPassword) || TextUtils.isEmpty(confirmPassword)) {
                    ToastUtils.showToast("密码不能为空");
                    return;
                }
                if (!StringUtilSub.isPassword(newPassword)) {
                    ToastUtils.showToast("密码必须是6-16位字母数字组合");
                    return;
                }
                if (!newPassword.equals(confirmPassword)) {
                    ToastUtils.showToast("两次密码不一致");
                    return;
                }
                String srcPassword = EncUtils.decrypt(mPreferences.getString(Globals.UUID, ""), mPreferences.getString(Globals.PASSWORD, ""));
                if (newPassword.equals(srcPassword)) {
                    ToastUtils.showToast("新密码与旧密码相同，无需重复修改");
                    return;
                }
                String uuid = mPreferences.getString(Globals.UUID, "");
                HttpMethods.getInstance().modifyPassword(uuid, newPassword, new ResetSubscriber(mContext, newPassword));
            }
        });
    }

    private static class ResetSubscriber extends BaseSubscriberAdapter<JSONObject> {
        private Context context;
        private String password;
        private WaitDialog waitDialog;

        public ResetSubscriber(Context context, String password) {
            this.context = context;
            this.password = password;
            waitDialog = new WaitDialog(context);
            waitDialog.setMessage("请稍后...");
        }

        @Override
        public void onSubscribe(Subscription s) {
            waitDialog.show();
            super.onSubscribe(s);
        }

        @Override
        public void onNext(JSONObject jsonObject) {
            waitDialog.dismiss();
            int status = jsonObject.optInt("status", 0);
            String message = jsonObject.optString("message", "");
            if (1 == status) {
                SharedPreferences mPreferences = YspPreferences.getInstance().getSharedPreferences();
                SharedPreferences.Editor editor = YspPreferences.getInstance().getSharedPreferences().edit();
                editor.putBoolean(Globals.PASSWORD_STATE, false)
                        .putString(Globals.PASSWORD, EncUtils.encrypt(mPreferences.getString(Globals.UUID, ""), password.getBytes())).apply();

                ToastUtils.showToast(TextUtils.isEmpty(message) ? "密码修改成功" : message);
                BaseUtil.hideKeyBoard(context);
                if (SystemUtils.isPad(context)) {
                    EventBus.getDefault().post(new YspEvent.PadClick(SettingsFragment.class.getName()));
                } else {
                    ((Activity) context).finish();
                }
            } else {
                DialogHelper.getAlertDialogCancelable(context, message, null).show();
            }
        }

        @Override
        public void onError(String errorMessage) {
            waitDialog.dismiss();
            ToastUtils.showToast(errorMessage);
            BaseUtil.hideKeyBoard(context);
        }
    }
}
